package com.moorwind.chartservice.utils
{
	import com.moorwind.chartservice.data.ChartResultVO;
	import com.moorwind.chartservice.data.ChartVO;
	
	import flash.events.EventDispatcher;
	
	public class ChartParser extends EventDispatcher
	{
		public static function parserChart(data:String):ChartResultVO
		{
			var xml:XML;
			var evt:ChartResultVO
			try
			{
				xml = new XML(data);
			}
			catch(e:Error)
			{
				evt = new ChartResultVO(null, true, "invalid data");
			}
			
			if(checkIsError(xml))
			{
				evt = new ChartResultVO(null, true, parserErrorMessageFromXML(xml));				
			}
			else
			{
				evt = new ChartResultVO(parserChartFromXML(xml));					
			}
			return evt;
		}
		
		public static function parserChartFromXML(xml:XML):Array
		{
			var a:Array = [];
			for each(var p:XML in xml..Chart)
			{
				var chart:ChartVO = new ChartVO();
				chart.userName = p.user_name;
				chart.userId = p.user_id;
				chart.userLink = p.user_link;
				chart.userImage = p.user_image;
				chart.userLargeImage = p.user_large_image;
				chart.platform = p.platform;
				chart.score = Number(p.score);
				a.push(chart);
			}
			return a;
		}
		
		public static function checkIsError(xml:XML):Boolean
		{
			return String(xml.isError) == "true";
		}
		
		public static function parserErrorMessageFromXML(xml:XML):String
		{
			return String(xml.message);
		}

	}
}